package com.zt.dev.userManage.service.impl;

import com.zt.dev.semiPhysicalEquipment.util.PageBean;
import com.zt.dev.userManage.entity.dto.UserAndTask;
import com.zt.dev.userManage.entity.enumvo.RoleEnum;
import com.zt.dev.userManage.entity.vo.User;
import com.zt.dev.userManage.mapper.TaskManageMapper;
import com.zt.dev.userManage.mapper.UserManageMapper;
import com.zt.dev.userManage.service.UserService;
import com.zt.dev.userManage.utils.DateUtil;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static javax.xml.bind.JAXBIntrospector.getValue;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserManageMapper userMapper;
    @Autowired
    private TaskManageMapper taskMapper;

    /**
     * 新增用户
     * @param user
     * @return
     */
    @Override
    public int insertUser(User user) {
        int result = 0;
        //判断是否已注册
        List<User> userList = userMapper.getUserByName(user.getUserName());
        if(userList.size() > 0) {
            return result;
        }else {
            //未注册，进而注册
            user.setCreateTime(DateUtil.getStringDateYmd());
            user.setFlag(0);
            result = userMapper.insertUser(user);
        }
        return result;
    }

    /**
     * 通过id多删除
     * @param ids
     * @return
     */
    @Override
    public int deleteById(Integer[] ids) {
        int result = 0;
        for(Integer id : ids){
            result = userMapper.deleteById(id);
            if(result > 0){
                result++;
            }else{
                result = 0;
            }
        }
        return result;
    }

    /**
     * 通过用户名查询信息
     * @param userName
     * @return
     */
    @Override
    public List<User> getUserByName(String userName) {
        return userMapper.getUserByName(userName);
    }

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    @Override
    public int updateUserById(User user) {
        int result = 0;
        User user1 = userMapper.getUserById(user.getId());
        //该用户存在
        if(user1 != null){
            result = userMapper.updateUserById(user);
        }else{
            result = 0;
        }
        return result;
    }

    /**
     * 分页查询人员列表
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Override
    public PageBean<User> getAllUser(int currentPage, int pageSize,String userName) {
        //获得总数
        int count = userMapper.getCount(userName);
        PageBean pageBean = PageBean.pageCommon(count, currentPage, pageSize);
        //起始 结束 页
        int start = (currentPage-1)*pageBean.getPageSize();
        int end = pageBean.getPageSize();
        //封装每页显示的数据
        List<User> userList = userMapper.getAllUser(start,end,userName);
        pageBean.setLists(userList);
        return pageBean;
    }

    /**
     * 通过id查询用户列表
     * @param id
     * @return
     */
    @Override
    public User getUserById(Integer id) {
        return userMapper.getUserById(id);
    }

    /**
     * 通过角色查询
     * @param role
     * @return
     */
    @Override
    public List<User> getUserByRole(Integer role) {
        return userMapper.getUserByRole(role);
    }

    /**
     * 读取excel文件
     * @param file
     * @return
     */
    @Override
    public List<User> uploadFileExcel(MultipartFile file) {
        int result =0;
        int row = 0;
        //返回结果集
        List<User> userList = new ArrayList<>();
        try {
            InputStream io = file.getInputStream();
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(io);
            XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
            XSSFRow titleCell = xssfSheet.getRow(0);
            row = xssfSheet.getLastRowNum();
            for(int i=1; i<=row;i++){
                XSSFRow xssfRow = xssfSheet.getRow(i);
                XSSFCell userName = xssfRow.getCell(0);
                XSSFCell realName = xssfRow.getCell(1);
                XSSFCell gendar = xssfRow.getCell(2);
                XSSFCell role = xssfRow.getCell(3);
                XSSFCell profession = xssfRow.getCell(4);
                XSSFCell unit = xssfRow.getCell(5);
                XSSFCell major = xssfRow.getCell(6);
                DataFormatter dataFormatter = new DataFormatter();
                dataFormatter.addFormat("###########", null);
                String tel  = dataFormatter.formatCellValue(xssfRow.getCell(7));

                User user = new User();
                user.setUserName(userName.getStringCellValue());
                user.setRealName(realName.getStringCellValue());
                user.setGendar(getValue(gendar)+"");
                //判断角色
                String role1 = role.getStringCellValue();
                user.setRole(RoleEnum.getCode(role1));
                user.setProfession(profession.getStringCellValue());
                user.setMajor(major.getStringCellValue());
                user.setUnit(unit.getStringCellValue());
                user.setTel(tel);
                user.setCreateTime(DateUtil.getStringDate());
                user.setFlag(1);//标识导入数据
                result = userMapper.insertUser(user);
                userList.add(user);
            }
            result++;

        } catch (IOException e) {
            e.printStackTrace();
        }
        if(result == row){
            return userList;
        }
        return null;
    }

    /**
     * 导入读取TXT文件
     * @param file
     * @return
     */
    @Override
    public int uploadFileTxt(MultipartFile file) {
        StringBuilder builder = new StringBuilder();
        // 使用ArrayList来存储每行读取到的字符串
        ArrayList<String> arrayList = new ArrayList<>();
        try {
            InputStreamReader reader = new InputStreamReader(new FileInputStream(new File(file.getOriginalFilename(),"UTF-8")));
            BufferedReader bufferReader = new BufferedReader(reader);
            String lineTxt;
            while((lineTxt = bufferReader.readLine())!= null){
                arrayList.add(lineTxt);
            }
            bufferReader.close();
            reader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对ArrayList中存储的字符串进行处理
        int length = arrayList.size();
        String[] array = new String[length];
        for(int i=0;i<length;i++){
            array[i] = arrayList.get(i);
        }
        return 0;
    }

    /**
     * 根据时间查询用户列表
     * @param startTime
     * @param endTime
     */
    @Override
    public List<UserAndTask> getUserByTime(String startTime, String endTime) {
        //数据源
        List<UserAndTask> userList = userMapper.getUserByTime(startTime, endTime);
        for(UserAndTask userAndTask : userList){
            userAndTask.setRoleName(RoleEnum.getType(userAndTask.getRole()));
        }
        return userList;


    }


}
